package com.liuzy.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

public class MyIP {
	public static void main(String[] args) {
		System.out.println("内网IP:" + getLocalIP());
		System.out.println("外网IP:" + getIntenetIP());
	}

	/**
	 * 获得本机外网IP
	 */
	private static String getIntenetIP() {
		InputStream ins = null;
		try {
			URL url = new URL("http://ip.cn");//http://1212.ip138.com/ic.asp
			URLConnection con = url.openConnection();
			con.setConnectTimeout(5000);
			con.setReadTimeout(5000);
			ins = con.getInputStream();
			InputStreamReader isReader = new InputStreamReader(ins, "UTF-8");
			BufferedReader bReader = new BufferedReader(isReader);
			StringBuffer webContent = new StringBuffer();
			String str = null;
			while ((str = bReader.readLine()) != null) {
				webContent.append(str);
			}
			int start = webContent.indexOf("<code>") + 6;
			int end = webContent.indexOf("</code>");
			return webContent.substring(start, end);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ins != null) {
				try {
					ins.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return null;
	}

	/**
	 * 获得本机内网IP
	 */
	private static String getLocalIP() {
		InetAddress ia;
		try {
			ia = InetAddress.getLocalHost();
			return ia.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return null;
	}
}
